﻿Imports AccessSvn.lib
Imports System.Threading
Imports System.Xml.Serialization
Imports System.IO

Imports AccessSvn.UI.MRU
Imports AccessSvn.lib.ModObjects
Imports System.Reflection
Imports System.Runtime.InteropServices

Public Class frmMain
    Implements IMRUClient

    Private mruManager As MRUManager
    Private writer As TextBoxWriter = Nothing

    Private accExporter As AccessSvnTransformer

    Private Sub InfoMessageReceived(ByVal msg As String)

        Me.txtResultsLog.Text = Me.txtResultsLog.Text & vbCrLf & msg

    End Sub

    Private Sub btnSelectSVNFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectSVNFolder.Click

        Me.fbSelectSVNFolder.Description = "Select SVN Folder"
        Me.fbSelectSVNFolder.ShowDialog()
        If Me.fbSelectSVNFolder.SelectedPath <> "" Then
            Me.txtSVNPath.Text = Me.fbSelectSVNFolder.SelectedPath
        End If
    End Sub

    Private Sub btnSelectAccessDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectAccessDB.Click

        'ofSelectAccessDB.CheckFileExists = True
        ofSelectAccessDB.CheckPathExists = True

        ofSelectAccessDB.Filter = "Access MDB|*.mdb|Access Project|*.adp|All Files|*.*"
        ofSelectAccessDB.FileName = String.Empty
        ofSelectAccessDB.Multiselect = False
        ofSelectAccessDB.Title = "Select Access File"
        ofSelectAccessDB.ShowDialog()

        If ofSelectAccessDB.FileName <> String.Empty Then
            Me.txtDatabase.Text = ofSelectAccessDB.FileName
        End If
    End Sub

    Private Sub btnCreateWorkFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles btnCreateWorkFile.Click

        Me.CreateAccessWorkfile()

    End Sub

    Private Sub btnFindStaleObjects_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
     Handles tsmiFindStaleQueries.Click

        writer = New TextBoxWriter(Me.txtResultsLog)
        Console.SetOut(writer)

        Dim staleQueryFinder As New QueryFilesWalker
        staleQueryFinder.RootPath = Me.txtSVNPath.Text

        Dim objNewThread As New Thread(AddressOf staleQueryFinder.walkFiles)
        objNewThread.IsBackground = True
        objNewThread.Start()

        AddHandler staleQueryFinder.SearchCompleted, AddressOf StaleQueryFound

    End Sub

    Private Sub StaleQueryFound(ByVal qname As String, ByVal isStale As Boolean)

        If isStale Then
            Console.WriteLine(qname & " " & isStale)
        End If

    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Text = Me.Text & " " & getMyVersion()
        Me.mruManager = New MRUManager()
        Call mruManager.Initialize(Me, Me.mnuFileMRU, "Software\\CodeGen.Org\\AccessSVN")
        ' Registry path to keep MRU list
        '
        '        // Optional. Call these functions to change default values:
        '
        Me.mruManager.CurrentDir = "....."          ' default is current directory
        Me.mruManager.MaxMRULength = 20            ' default is 10
        Me.mruManager.MaxDisplayNameLength = 50     ' default is 40
        If checkCommandLine() = False Then
            'keep this after mruManager init
            If My.Settings.ReopenLastProject AndAlso My.Settings.LastProjectFilePath <> "" Then
                Me.LoadProjectFromXmlInfoFile(My.Settings.LastProjectFilePath)
            End If
        End If

    End Sub
    Private Function checkCommandLine() As Boolean

        If My.Application.CommandLineArgs.Count > 0 Then
            If My.Application.CommandLineArgs.Item(0) = "CreateWorkFile" Then
                AppContext.current.RootSVNPath = My.Application.CommandLineArgs.Item(1)
                Me.accExporter = New CreateAccessDBFromSVN
                accExporter.Transform()
                Return True

            ElseIf My.Application.CommandLineArgs.Item(0) = "CreateSVNSources" Then

                'Me.txtSourceDatabase.Text = My.Application.CommandLineArgs.Item(1)
                Me.txtSVNPath.Text = My.Application.CommandLineArgs.Item(2)
                Me.exportSVNSources()

                Return True

            End If
        End If

        Return False
    End Function
    Private Sub tsmiOpenProject_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles tsmiOpenProject.Click

        ofSelectAccessDB.CheckFileExists = True
        ofSelectAccessDB.CheckPathExists = True

        ofSelectAccessDB.Filter = "XML Project File|*.xml|All Files|*.*"
        ofSelectAccessDB.FileName = String.Empty
        ofSelectAccessDB.Multiselect = False
        ofSelectAccessDB.Title = "Select Project File"
        ofSelectAccessDB.ShowDialog()

        If ofSelectAccessDB.FileName <> String.Empty Then

            Me.LoadProjectFromXmlInfoFile(ofSelectAccessDB.FileName)

            Me.mruManager.AddMRUMenuItem(ofSelectAccessDB.FileName)

        End If

    End Sub

    Private Sub CreateFromSVNSourcesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmiCreateFromSVNSources.Click
        Me.CreateAccessWorkfile()
    End Sub

    Private Sub LoadProjectFromXmlInfoFile(ByVal confFile As String) _
       Implements MRU.IMRUClient.OpenMRUFile

        Dim f As New IO.FileInfo(confFile)
        If f.Exists = False Then Return

        Dim confPath As String = f.Directory.FullName
        AppContext.current.RootSVNPath = confPath
        'AppContext.current.xmlConfigFilename = confFile

        Me.txtDatabase.Text = AppContext.current.projectInfo.AccessDatabaseName
        Me.txtSVNPath.Text = AppContext.current.RootSVNPath
        Me.txtProjectName.Text = AppContext.current.projectInfo.ProjectName
        Dim s As New SVNClient
        s.rootSvnProjectPath = AppContext.current.RootSVNPath
        Me.txtSVNRevisionNo.Text = CStr(s.getSVNCurrentRevision)

        Dim app As Microsoft.Office.Interop.Access.Application
        Try
            app = New Microsoft.Office.Interop.Access.Application
            app.OpenCurrentDatabase(Me.txtSVNPath.Text & "\" & Me.txtDatabase.Text, False)
            Me.txtAccessRevision.Text = AppContext.current.getAccessProperty(app, "svnRevision")
        Finally
            app.Quit()
            If app IsNot Nothing Then Marshal.ReleaseComObject(app)
            app = Nothing
        End Try

        My.Settings.LastProjectFilePath = confFile

    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmiExit.Click

        Application.Exit()

    End Sub

    Private Sub ReopenLastProjectToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmiReopenLastProject.Click

        Me.tmiReopenLastProject.Checked = Not Me.tmiReopenLastProject.Checked
        My.Settings.ReopenLastProject = Me.tmiReopenLastProject.Checked

    End Sub

    Private Sub tsmiSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles tsmiSave.Click

        AppContext.current.projectInfo.ProjectName = Me.txtProjectName.Text
        AppContext.current.projectInfo.AccessDatabaseName = Me.txtDatabase.Text
        AppContext.current.projectInfo.AccessDatabasePassword = Me.txtSVNRevisionNo.Text
        AppContext.current.projectInfo.ProjectName = Me.txtProjectName.Text

        Me.saveProjectInfo()

    End Sub

    Private Sub saveProjectInfo()

        Dim fileWriter As StreamWriter = New StreamWriter(Me.txtSVNPath.Text & "\AccessSvnProjectInfo.xml", _
             False, System.Text.Encoding.UTF8)

        Dim x As XmlSerializer = New XmlSerializer(AppContext.current.projectInfo.GetType())

        Try
            x.Serialize(fileWriter, AppContext.current.projectInfo)

        Finally
            fileWriter.Close()

        End Try

    End Sub

    'Private Sub svnUpdate()

    '    Dim cSVNClient As New SVNClient
    '    cSVNClient.rootSvnProjectPath = Me.txtSVNPath.Text
    '    cSVNClient.svnExecutablePath = AppContext.current.determineTortoisePath
    '    cSVNClient.Update()

    'End Sub

    Private Sub CreateAccessWorkfile()
        'create access workfile
        Me.txtResultsLog.Text = String.Empty
        Me.writer = New TextBoxWriter(Me.txtResultsLog)

        Console.SetOut(writer)

        Me.accExporter = New CreateAccessDBFromSVN
        Dim accfilename As String = CType(Me.accExporter, CreateAccessDBFromSVN).getFinalAccessFilename
        If File.Exists(accfilename) Then
            Dim anr As MsgBoxResult = MsgBox("File " & accfilename & " exists, overwrite?", CType(vbQuestion + vbYesNo, MsgBoxStyle))
            If anr = MsgBoxResult.No Then Exit Sub
            If anr = MsgBoxResult.Yes Then
                File.Delete(accfilename)
            End If

        End If

        AddHandler accExporter.TransformStarted, AddressOf TransformStarted
        AddHandler accExporter.TransformEnd, AddressOf TransformEnd
        AddHandler accExporter.TransformError, AddressOf TransformError

        Dim objNewThread As New Thread(AddressOf accExporter.Transform)
        objNewThread.IsBackground = True
        objNewThread.Start()

    End Sub

    Private Function validateAndSaveProjectInfo() As Boolean
        If String.IsNullOrEmpty(Me.txtProjectName.Text) Then
            MsgBox("Please give a project name.", MsgBoxStyle.Critical)
            Return False
        End If

        If IO.File.Exists(Me.txtDatabase.Text) = False Then
            MsgBox("Database Fle does not exist", MsgBoxStyle.Critical)
            Return False
        End If
        If IO.Directory.Exists(Me.txtSVNPath.Text) = False Then
            MsgBox("SVN Root Folder not exist", MsgBoxStyle.Critical)
            Return False
        End If

        AppContext.current.projectInfo.ProjectName = Me.txtProjectName.Text
        AppContext.current.projectInfo.AccessDatabaseName = Me.txtDatabase.Text
        AppContext.current.projectInfo.AccessDatabasePassword = Me.txtSVNRevisionNo.Text
        Me.saveProjectInfo()

        Return True

    End Function

    Public Sub exportSVNSources()

        'Me.txtResultsLog.Text = String.Empty
        Me.writer = New TextBoxWriter(Me.txtResultsLog)
        Console.SetOut(Me.writer)

        Me.accExporter = New AccessDBToSVNSources
        CType(accExporter, AccessDBToSVNSources).sourceDatabase = AppContext.current.getAccessDatabaseFullName
        AppContext.current.RootSVNPath = Me.txtSVNPath.Text

        AddHandler accExporter.TransformStarted, AddressOf TransformStarted
        AddHandler accExporter.TransformEnd, AddressOf TransformEnd
        AddHandler accExporter.TransformError, AddressOf TransformError
        Dim objNewThread As New Thread(AddressOf accExporter.Transform)
        objNewThread.IsBackground = True
        objNewThread.Start()

    End Sub

    Private Sub TransformError(ByVal msg As String)
        Console.WriteLine("Error on Operation:" & msg)
    End Sub

    Private Sub TransformEnd()
        If Me.btnCancel.InvokeRequired Then
            Dim d As New delegateHideShowButton(AddressOf hideShowButton)
            Me.btnCancel.Invoke(d, New Object() {False})
        Else
            Me.btnCancel.Visible = False
        End If

        Console.WriteLine("Operation Ended on " & Now)
    End Sub

    Private Sub TransformStarted()

        If Me.btnCancel.InvokeRequired Then
            Dim d As New delegateHideShowButton(AddressOf hideShowButton)
            Me.btnCancel.Invoke(d, New Object() {True})
        Else
            Me.btnCancel.Visible = True
        End If
        Console.WriteLine("Operation Starting on " & Now)
    End Sub




    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If Me.accExporter IsNot Nothing Then
            Me.accExporter.isCancelled = True
        End If
    End Sub

    Private Sub cmdSVNCommit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSVNCommit.Click



    End Sub

    Delegate Sub delegateHideShowButton(ByVal show As Boolean)

    Private Sub hideShowButton(ByVal show As Boolean)

        Me.btnCancel.Visible = show

    End Sub

    Private Function getMyVersion() As String
        Return Assembly.GetExecutingAssembly.GetName.Version.ToString
    End Function

    Private Sub tsSVNUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsSVNUpdate.Click
        'Me.txtResultsLog.Text = String.Empty

        Me.txtResultsLog.Text = String.Empty
        Me.writer = New TextBoxWriter(Me.txtResultsLog)
        Console.SetOut(Me.writer)

        Me.accExporter = New UpdateAccessDBFromSVN
        AppContext.current.RootSVNPath = Me.txtSVNPath.Text

        AddHandler accExporter.TransformStarted, AddressOf TransformStarted
        AddHandler accExporter.TransformEnd, AddressOf TransformEnd
        AddHandler accExporter.TransformError, AddressOf TransformError
        Dim objNewThread As New Thread(AddressOf accExporter.Transform)
        objNewThread.IsBackground = True
        objNewThread.Start()

    End Sub
End Class
